<?php
/**
 * 进销存系统预约单模块对外API方法
 * Created by PhpStorm.
 * User: kelvin
 * Date: 18-1-4
 * Time: 下午3:50
 */
class PurchaseApi
{
    /**
     *  分销直上系统对接：推送预约单到分销直上系统
     *  作者:kelvin
     * */
    public static function purchasePull($id)
    {
        if($id && !empty($id)){
            $sql = "SELECT a.id,a.purchaseorder_date,a.createtype,a.purchaseplaner,a.supplier_id,a.money,a.warehouseid,
                a.coin,a.remark,b.purchaseorder_id,b.sku,b.sku_name,b.single_price,b.quantity,b.money 'de_money',b.arrive_date
                FROM purchaseorders a 
                LEFT JOIN purchaseorder_details b ON b.purchaseorder_id = a.id
                WHERE a.id = $id";
            $result = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array();
            $data = array();
            $coin = self::getCoin();
            foreach ($result as &$v){
                if(isset($data['product'])){
                    $data['product'][] = array(
                        'unifiedSku' =>$v['sku'],
                        'proName' =>$v['sku_name'],
                        'price' =>$v['single_price'],
                        'reqNum' =>$v['quantity'],
                        'lastArvDate' =>$v['arrive_date'],
                    );
                }else{
                    $str = Erpuser::mail_by_id($v['purchaseplaner']);
                    $data = array(
                        'notId'=>$v['id'],
                        'supplierId'=>$v['supplier_id'],
                        'supplierName'=>supplierskus::getNameByIdForVmi($v['supplier_id']),
                        'arrivalTime'=>$v['arrive_date'],
                        'address'=>self::getWarehouseAddress($v['warehouseid']),
                        'puManName'=>Erpuser::nick_by_id($v['purchaseplaner']),
                        'conPhone'=>substr($str,0,strrpos($str,'@')),
                        'coin'=>$coin[$v['coin']],
                        'puRemark'=>$v['remark'],
                        'createTime'=>$v['purchaseorder_date'],
                        'orderType'=>'10',
                        'product'=>array(
                            array(
                            'unifiedSku' =>$v['sku'],
                            'proName' =>$v['sku_name'],
                            'price' =>$v['single_price'],
                            'reqNum' =>$v['quantity'],
                            'lastArvDate' =>$v['arrive_date'],
                            'imageUrl' =>'1234',
                        ))
                    );
                }

            }
            $data = json_encode($data);
            $key = '6a0ec862b88a5ea336d10a6d9eaa2c89';
            $get = array('c' => 'vmi', 'a' => 'setOrder');
            $post = $data;
            $md5 = md5(join($get) . $post . $key);
            $host = Kohana::$config->load('server_url')->get('server_pro');
            $url = $host . '/api/index.php?c=vmi&a=setOrder&md5=' . $md5;
            $re = self::post_curl($url,$data);
            return $re;
        }else{
            return array('code'=>301,'msg'=>'数据有问题');
        }
    }
    /**
     *  分销直上系统对接：接收供应商发货信息
     *  作者:kelvin
     * */
    public static function purchaseLogisticsGet($data = array())
    {
        if(is_array($data) && !empty($data)){
            if(self::checkPuId($data['notId'])==false){
                return array('code'=>501,'msg'=>$data['notId'].'预约单号不存在');
            }
            $result = array(
                'purchaseorder_id' =>$data['notId'],
                'logistics' =>$data['logistics'],
                'logistics_name' =>$data['logisticsName'],
                'track_no' =>$data['trackNo'],
                'arrival_time' =>$data['arrivalTime'],
                'data' =>json_encode($data['data']),
                'create_time' =>date('Y-m-d H:i:s'),
            );
//            if(DB::select('id')->from('purchaseorder_logistics')->where('purchaseorder_id','=',$data['notId'])->execute('newerp')->current()){
//                $id =  DB::update('purchaseorder_logistics')->set($result)->where('purchaseorder_id','=',$data['notId'])->execute('newerp');
//            }else{
            $id = DB::insert('purchaseorder_logistics',array_keys($result))
                ->values(array_values($result))
                ->execute('newerp');
//            }
            if($id!=false){
                return array('code'=>200,'msg'=>'操作成功');
            }else{
                return array('code'=>400,'msg'=>'数据库操作失败');
            }
        }else{
            return array('code'=>500,'msg'=>'参数错误');
        }


    }
    /**
     *  分销直上系统对接：推送退货数据到分销直上系统
     *  作者:kelvin
     * */
    public static function supplierReturnsPull($id)
    {
        if($id){
            $returnList = DB::select('*')->from('supplier_returns_approval')->where('id','=',$id)->execute('newerp')->current();
            $logistics = json_decode($returnList['logistics_json'],true);
            $params = array(
               'notId' => $returnList['id'],
//                'notId'=>'ID03433904943',
               'supplierId' => $returnList['supplier_id'],
               'logisticsName' => $logistics['logisticsName'],
               'trackNo' => $logistics['trackNo'],
               'address' => $logistics['address'],
               'conMan' => $logistics['contact'],
               'conPhone' => $logistics['phone'],
               'shipTime' => $returnList['ship_time'],
               'unifiedSku' => $returnList['sku'],
               'replenishNum' => $returnList['return_qty'],
               'nowTime' => date('Y-m-d H:i:s'),
               'remark' => $returnList['remark'],
            );
            if($params){
                $data = json_encode($params);
                $key = '6a0ec862b88a5ea336d10a6d9eaa2c89';
                $get = array('c' => 'vmi', 'a' => 'returnSku');
                $post = $data;
                $md5 = md5(join($get) . $post . $key);
                $host = Kohana::$config->load('server_url')->get('server_pro');
                $url = $host . '/api/index.php?c=vmi&a=returnSku&md5=' . $md5;
                $re = self::post_curl($url,$data);
                return $re;
            }else{
                return array('code'=>301,'msg'=>'数据有问题');
            }
        }

    }

    /**
     *  分销直上系统对接：通过 不合格处理单 unqualified_deal_invoices id
     *  推送不良品数据到分销直上系统
     *  作者:kelvin
     * */
    public static function supplierReturnsPullBad($id)
    {
        if($id){
            //不合格处理单信息
            $unqualified = DB::select('purchaseorder_id','check_detail_id','warehouseid','sku','quantity','check_remark','deal_time')
                ->from('unqualified_deal_invoices')
                ->where('id','=',$id)
                ->execute('newerp')
                ->current();
            $warehouseid = $unqualified['warehouseid'];
            $check_detail_id = $unqualified['check_detail_id'];
            //质检明细表
            $check_detail = DB::select('recieve_detail_id')
                ->from('check_quality_details')
                ->where('id','=',$check_detail_id)
                ->execute('newerp')
                ->current();
            $recieve_detail_id = $check_detail['recieve_detail_id'];
            //收获明细表
            $recieve_details = DB::select('recieve_invoice_id')
                ->from('recieve_details')
                ->where('id','=',$recieve_detail_id)
                ->execute('newerp')
                ->current();
            $recieve_invoice_id = $recieve_details['recieve_invoice_id'];
            //收货单信息
            $recieve_invoices = DB::select('track_no')
                ->from('recieve_invoices')
                ->where('id','=',$recieve_invoice_id)
                ->execute('newerp')
                ->current();
            //预约单信息
            $purchaseorders =  DB::select('supplier_id')
                ->from('purchaseorders')
                ->where('id','=',$unqualified['purchaseorder_id'])
                ->execute('newerp')
                ->current();
            //预约单物流信息
            $purchaseorder_logistics = DB::select('logistics_name')
                ->from('purchaseorder_logistics')
                ->where('purchaseorder_id','=',$unqualified['purchaseorder_id'])
                ->and_where('track_no','=',$recieve_invoices['track_no'])
                ->execute('newerp')
                ->current();
            //质检分销直上不良品信息
            $check_quality_fx_msg = DB::select('badProType','badTypeName')
                ->from('check_quality_fx_msg')
                ->where('recieve_detail_id','=',$recieve_detail_id)
                ->execute('newerp')
                ->current();
            //供应商收货信息
            $supplier = supplierskus::getSupplierAddress($purchaseorders['supplier_id']);
            $params = array(
               'notId' => $unqualified['purchaseorder_id'],
               'supplierId' => $purchaseorders['supplier_id'],
               'logisticsName' => $purchaseorder_logistics['logisticsName'],
               'trackNo' => $recieve_invoices['track_no'],
               'badProType' => $check_quality_fx_msg['badProType'],
               'badTypeName' => $check_quality_fx_msg['badTypeName'],
               'address' => $supplier['address'],
               'conMan' => $supplier['contact'],
               'conPhone' => $supplier['phone'],
               'shipTime' => $unqualified['deal_time'],
               'unifiedSku' => $unqualified['sku'],
               'returnNum' => $unqualified['quantity'],
               'nowTime' => date('Y-m-d H:i:s'),
               'remark' => $unqualified['check_remark'],
            );
            if($params){
                $data = json_encode($params);
                $key = '6a0ec862b88a5ea336d10a6d9eaa2c89';
                $get = array('c' => 'vmi', 'a' => 'returnSku');
                $post = $data;
                $md5 = md5(join($get) . $post . $key);
                $host = Kohana::$config->load('server_url')->get('server_pro');
                $url = $host . '/api/index.php?c=vmi&a=returnSku&md5=' . $md5;
                $re = self::post_curl($url,$data);
                return $re;
            }else{
                return array('code'=>301,'msg'=>'数据有问题');
            }
        }

    }

    /**
     *  分销直上系统对接：接收退供应商收货确认信息
     *  作者:kelvin
     * */
    public static function supplierReturnsGet($ids = array())
    {
        if(is_array($ids) && !empty($ids)){
            $returnList = DB::select('*')->from('supplier_returns_approval')->where('id','in',$ids)->execute('newerp')->as_array();
            $u_id = array();
            $e_id = array();
            foreach ($returnList as $k =>$v){
                if($v['status']==80){
                    $u_id[] = $v['id'];
                }else{
                    $e_id[] = $v['id'];
                }
            }
            DB::update('supplier_returns_approval')->set('status','=','90')->where('id','in',$u_id)->execute('newerp');
        }

    }
    /**
     *  获取仓库地址
     *  作者:kelvin
     * */
    public static function getWarehouseAddress($id)
    {
        $result = DB::select('*')->from('statusdics')->where('colum_name','=','warehouseid_add')->where('number','=',$id)->execute('newerp')->current();
        return $result?$result['value']:'';
    }
    /**
     *  接口调用
     *      url 地址
     *      data 数据
     *  作者:kelvin
     * */
    public static function post_curl($url,$data){
        //请求接口
        $handle = curl_init();
        curl_setopt($handle,CURLOPT_URL,$url);
        curl_setopt($handle,CURLOPT_RETURNTRANSFER,TRUE);
        curl_setopt($handle,CURLOPT_CONNECTTIMEOUT,60);
        curl_setopt($handle,CURLOPT_TIMEOUT,90);
        curl_setopt($handle,CURLOPT_MAXREDIRS,3);
        curl_setopt($handle,CURLOPT_POST,TRUE);
        curl_setopt($handle,CURLOPT_POSTFIELDS,$data);
        curl_setopt($handle,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_0);
        curl_setopt($handle,CURLOPT_HEADER,FALSE);    //不返回头信息
        $response = curl_exec($handle);
        curl_close($handle);
        $result =json_decode($response,true);
        return $result;
    }
    /**
     *  币总
     *  作者:kelvin
     * */
    public static function getCoin()
    {
        return array(
            '1'=>'人民币',
            '2'=>'美元',
            '3'=>'港币',
        );
    }
    /**
     *  检查预约单号是否存在
     *  作者:kelvin
     * */
    public static function checkPuId($id)
    {
        if($id && DB::select('id')->from('purchaseorders')->where('id','=',$id)->execute('newerp')->current()){
            return true;
        }else{
            return false;
        }
    }
    /**
     *  验证签名 $key = md5('9610vmi');
     *  作者:kelvin
     * */
    public static function check_sign($data,$key='52275b50893f4d33bde2dfaa44144735')
    {
        if(md5($data['data'].$key)==$data['sign']){
            return true;
        }else{
            return false;
        }
    }
}